<?php

namespace Modules\Inventory\Repository;

use Illuminate\Support\Facades\DB;
use Modules\Inventory\Models\InventoryOrderDetail;

/**
 * 盘点单明细相关
 * Class InventoryOrderRepository
 * @package Modules\Inventory\Repository
 */
class InventoryOrderDetailRepository
{
    /**
     * 盘点单明细
     * @param $request
     * @return mixed
     */
    static public function getList($request){

        $builder = self::getWhere($request);

        $limit = isset($request['limit']) ? $request['limit'] : 100;

        $list = $builder->with(['material','locations','wms'])->orderBy('id','desc')->paginate($limit)->toArray();

        return $list;

    }

    /**
     * 查询条件拼接
     * @param $request
     * @return InventoryOrderDetail
     */
    static public function getWhere($request){

        $builder = new InventoryOrderDetail();

        $canSearchFields = $builder->getFields();

        if(isset($request['gain_loss']) && $request['gain_loss'] != ''){

            if($request['gain_loss'] == 1){
            //盘盈
                $builder = $builder->whereColumn('stock_qty','>','qty');
            }elseif($request['gain_loss'] == 2){
            //盘亏
                $builder = $builder->whereColumn('stock_qty','<','qty');
            }
        }

        foreach ($request as $key => $val){

            if(!in_array($key,$canSearchFields) || $val == ''){
                continue;
            }

            $builder = $builder->where($key,$val);

        }

        return $builder;

    }

    /**
     * 获取盘点单明细差异数
     * @param array $orderId
     * @return mixed
     */
    static public function getDiffQtyByOrderId(array $orderId){
        return InventoryOrderDetail::select('material_no','wms_code',DB::raw('sum(qty) as qty'),DB::raw('sum(stock_qty) as stock_qty'),DB::raw('sum(stock_qty - qty) as diff_qty'))
            ->whereIn('order_id',$orderId)
            ->with(['material','wms'])
            ->groupBy('material_no','wms_code')
            ->get();
    }

}
